/**
 * 构造图表数据
 */

// 根据类型，构造数据
const typeToCreate = {
  bar: function(data) {
    return utils.data.call(this, data)
  },
  line: function(data) {
    return utils.data.call(this, data)
  },
  pie: function(data) {
    return utils.dataForPie.call(this, data)
  },
  donut: function(data) {
    return utils.data.call(this, data)
  }
}

// 不同的数据结构
const utils = {
  data: function(data) {
    let { dimensions, measures } = this.chartOptions
    if (!dimensions && !measures) {
      return {}
    }

    dimensions = Object.assign({}, dimensions, {
      data: data.map((dataitem) => {
        return dataitem[dimensions.field]
      })
    })

    measures.map((item, index) => {
      measures[index] = Object.assign({}, item, {
        data: data.map((dataitem) => {
          return dataitem[item.field]
        })
      })
    })

    return {
      dimensions,
      measures
    }
  },
  dataForPie: function(data) {
    let that = this
    let pieData = utils.data.call(that, data)
    let { dimensions, measures } = pieData
    let legendSelected = {}, sums = 0
    measures.length &&
      measures[0].data.map((item, index) => {
        sums += parseFloat(item ? item : 0) 
        item == 0 && (legendSelected[dimensions.data[index]] = false)
      })

    return sums ? pieData : { ...pieData, legend: { selected: legendSelected } }
  }
}

class createChartData {
  constructor(chart, chartOptions) {
    this.chart = chart
    this.chartOptions = chartOptions
    this.legend = null
  }

  create(data, type) {
    let { legend , ...chartdata } = typeToCreate[type]?.call(this, data)
    legend && (this.legend = legend)
    return chartdata
  }
}

export default createChartData
